/**
 * 模仿简单的聊天室应用
 */

var net = require('net'); 
var HOST = '192.168.3.31';
var PORT = 5566;
var clientList = [];

/**
 * 创建服务器
 * 
 */
var server = net.createServer();

server.on('connection',function(client){
    clientList.push(client);
    client.name = client.remoteAddress + ':' + client.remotePort;
    broadcast('hi,welcome'+ client.name +'join in\r\n',client);
    client.write('hi,welcome' + client.name +'join in\r\n'); 

    /**
     * 监听data事件
     */
    client.on('data',function(data){
        broadcast(client.name + 'say: ' + data + '!\r\n');

    });
    /**
     * 监听end事件
     */
    client.on('end',function(){
        broadcast('嘿,欢送' + client.name+ '离开！\r\n');
    })

})

/**
 * 定义广播发送通知broadcast函数
 * 
 * @param message
 * @param client
 */

function broadcast(message,client){
    var cleanup = [];
    for(var i=0,len= clientList.length;i<len;i++){
        if(client != clientList[i]){
            if(clientList[i].writable){
                clientList[i].write(message);   //向客户端发送数
            }else{
                cleanup.push(clientList[i]);
                clientList[i].destroy();  //清除客户端socket
            }
        }
    }
    for(var i =0,len=cleanup.length;i<len;i++){
        clientList.splice(clientList.indexOf(cleanup[i],1));  //删除客户端socket
    }
}

/**
 * 监听
 */

server.listen(PORT,HOST,function(){
    console.log('服务器启动了'+PORT+'端口!')
});

